<template>
  <div class="excel">
    导入详情
    <excel :on-success="onSuccess" :before-upload="beforeUpload" />
  </div>
</template>

<script>
import { batchUser } from '@/api/employees'
export default {
  methods: {
    // excel表上传文件函数
    beforeUpload(file) {
      const size = file.size / 1024 / 1024
      if (size > 2) {
        this.$message.warning('文件大小超过2M')
      } else {
        // 返回上传文件，调用onSuccess函数
        return file
      }
    },
    async onSuccess({ header, results }) {
      console.log(header, results)
      const obj = {
        '入职日期': 'timeOfEntry',
        '姓名': 'username',
        '工号': 'workNumber',
        '手机号': 'mobile',
        '转正日期': 'correctionTime'
      }
      // 将中文的属性改为英文的属性
      const res = results.map(item => {
        // 定义一个转换之后的对象
        const obj1 = {}
        Object.keys(obj).forEach(subitem => {
          // subitem:上面obj的键（入职日期&姓名....）
          if (obj[subitem] === 'timeOfEntry' || obj[subitem] === 'correctionTime') {
            const timeDay = this.conversion(item[subitem])
            // timeData.setFullYear = (timeData.getFullYear - 70)
            console.log(timeDay)
            obj1[obj[subitem]] = timeDay
          } else {
            obj1[obj[subitem]] = item[subitem]
          }
        })
        return obj1
      })

      // 发送请求到服务器
      await batchUser(res)
      // 提示新增成功
      this.$message.success('导入成功')
      // 跳回员工页面
      this.$router.push('/employees')
    },
    conversion(day) {
      const timeData = new Date((day - 1) * 24 * 60 * 60 * 1000)
      return new Date(timeData.setFullYear(timeData.getFullYear() - 70))
    }
  }

}
</script>

<style lang="scss" scoped>
.excel{

}
</style>
